#pragma once
#ifndef __USE_GNU
	#define __USE_GNU
#endif
#include <dinfra/init_fin.h>
#include <pthread.h>

/* METALC共享库使用 */
#define DEF_PTHREADALT_INIT_METALC_SOLIB		\
static void sys_init(void);		\
MAY_UNUSED static void sys_fin(void);	\
static void cflow_init(void);		\
MAY_UNUSED static void cflow_fin(void);	\
static pthread_key_t thread_init_key;	\
static void thread_destructor(void *_){\
	(void) _;\
	cflow_fin();\
}\
static void proc_initializer(){\
	sys_init();\
	pthread_key_create(&thread_init_key, thread_destructor);\
}\
static void reg_thread_destructor(){\
	pthread_setspecific(thread_init_key, (void *)-1);\
}\
static void __thread_initializer(){\
	cflow_init();\
	reg_thread_destructor();\
}

#define DEF_PTHREADALT_INIT					\
DEF_PTHREADALT_INIT_METALC_SOLIB;				\
static int swi = 0;\
__attribute__((destructor)) void __pthreadalt_proc_destructor(){\
	if (swi){\
		/* fprintf(stderr, "proc destructor, execute initializer times %d\n", swi); */\
		cflow_fin();\
		sys_fin();\
		swi = 0;\
	}\
}\
void thread_initializer(){\
	__thread_initializer();\
}\
__attribute__((constructor)) void __pthreadalt_init_contructor() { \
	if (!swi){\
		/* fprintf(stderr, "thread constructor \n"); */\
		proc_initializer(); \
		/*fprintf(stderr, "start thread_initializer \n");*/ \
		thread_initializer();\
	}\
	swi++;\
}
